import { ExclamationCircleOutlined, PlusOutlined, PaperClipOutlined } from '@ant-design/icons';
import { Button, Divider, Space, Tree, message, Modal, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { Link } from 'umi';

import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import DetailModel from './components/DetailModel';
import { queryPatrolRecord, updatePatrolRecord, addPatrolRecord, removePatrolRecord } from '@/services/patrolrecord';
import { patrolJobList } from '@/services/patroljob';
import { userList } from '@/services/user';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addPatrolRecord(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updatePatrolRecord(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const handleRemove = async (fields: any) => {
  const hide = message.loading('正在删除');
  try {
    await removePatrolRecord({ id: fields.id });
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const { confirm } = Modal;

const TableList: React.FC<{}> = () => {

  const actionRef = useRef<ActionType>();

  const [userArray, setUserArray] = useState<API.UserItem[]>([]);
  const [patrolJobArray, setPatrolJobArray] = useState<API.PatrolJob[]>([]);

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});

  const columns: ProColumns<API.PatrolRecord>[] = [
    {
      title: '任务名称',
      dataIndex: 'jobName',
      render: (_,record) => 
      <Link to={`patrolRecordDetails/${record.id}/${record.jobId}`} > {_}</Link>
    }, 
   
 
    {
      title: '巡检人',
      dataIndex: 'userName',
    },
    {
      title: '处理意见',
      dataIndex: 'comment',
    },
    {
      title: '值班领导',
      dataIndex: 'dutyLeaderName',
    },
    {
      title: '领导是否确认',
      dataIndex: 'isConform',
      valueEnum: {
        1: { text: '是' },
        0: { text: '否' },
      },
      hideInSearch: true,
    },
    {
      title: '巡检时间',
      dataIndex: 'patrolTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            key="editable"
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          {/* <a onClick={async () => {
            handleDetailModalVisible(true);
            setFormValues(record);
          }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <Link to={`patrolRecordDetails/${record.id}/${record.jobId}`} >巡检项目</Link>
          <Divider type="vertical" /> */}
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const setStateData = async () => {
    const patrol = await patrolJobList();
    setPatrolJobArray(patrol);
    const users = await userList();
    setUserArray(users);
  };

  useEffect(() => {
    setStateData();
  }, []);

  return (
    <>
      <ProTable
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        tableAlertRender={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        toolbar={{
          settings: []
        }}
        search={{
          labelWidth: 'auto',
        }}
        rowSelection={{}}
        request={(params) => queryPatrolRecord({ ...params })}
        columns={columns}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            setFormValues({});
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        userList={userArray}
        patrolJobList={patrolJobArray}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          userList={userArray}
          patrolJobList={patrolJobArray}
        />
      ) : null}
      {formValues && Object.keys(formValues).length ? (
        <DetailModel
          onCancel={() => {
            handleDetailModalVisible(false);
            setFormValues({});
          }}
          modalVisible={detailModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default TableList;
